package com.zhku.zhny.util;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		// 获取请求方法名
		String methodName = request.getParameter("method");
		try {
			// 通过反射拿到目标方法
			Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			// 执行目标方法
			Object invoke = method.invoke(this, request, response);
			if(invoke!=null) {
				String result = (String)invoke;
				String[] split = result.split(":");
				if("redirect".equals(split[0])) {
					response.sendRedirect(request.getContextPath()+split[1]);
				}else{
					request.getRequestDispatcher(split[1]).forward(request, response);
				}
			}
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
			request.getRequestDispatcher("/404.html").forward(request, response);
		}
	}
		
}
